#include <sys/epoll.h>

#include "SerialPortCommunicator485.h"
#include "ErrorCode.h"



SerialPortCommunicator485::SerialPortCommunicator485(const char* const deviceName) : SerialPortCommunicator(deviceName) {	//outer serial port
    //switchRs485(true);

    closeFd(deviceFd);

    mpollFd = ::epoll_create(1);
}






SerialPortCommunicator485::~SerialPortCommunicator485() {
    ::close(mpollFd);
}




ssize_t SerialPortCommunicator485::read(const std::string& exceptionTip, void * buffer, const size_t length) noexcept {
    ssize_t returnlength;

    deviceFd = reopen();
    switchRs485(true);
    setPort(StringUtility::EMPTY_STRING);

    epoll_event event;
    event.events = EPOLLIN;
    ::epoll_ctl(mpollFd, EPOLL_CTL_ADD, deviceFd, &event);
    int waitResult = ::epoll_wait(mpollFd, &event, 1, 100);
    if (1 == waitResult) {
        returnlength = SerialPortCommunicator::read(exceptionTip, buffer, length);
    } else {
        returnlength = -1;
        LOG_DEDUG("%s,wait for read failed", exceptionTip.data());
    }
    ::epoll_ctl(mpollFd, EPOLL_CTL_DEL, deviceFd, nullptr);

    closeFd(deviceFd);
    deviceFd = -1;

    return returnlength;
}





/*
ssize_t SerialPortCommunicator::read(const std::string& exceptionTip, void * buffer, const size_t length) noexcept {

    ssize_t result = 0;
    if (length < 1){
        return result;
    }

    ssize_t readed = 0;
     uint8_t* const start = static_cast<uint8_t*> (buffer);
     uint8_t* iterator = start;
     uint8_t* const endIterator = iterator + length;
    do {
        readed = ::read(deviceFd, iterator, sizeof(uint8_t));
        //LOG_DEDUG("readed:%zd,[%u,%c]", readed, *iterator, *iterator);
    } while (0 < readed && '<' != *iterator);
    if(0 >= readed) {
        LOG_ERROR("begining readed size[%zd]!", readed);
        result = -1;
    } else {
        while(endIterator != ++iterator) {
            readed = ::read(deviceFd, iterator, sizeof(uint8_t));//
            if(0 >= readed) {
                LOG_ERROR("response text readed size[%zd]!", readed);
                result = -1;
                break;
            }
            //printf("recv data: %c\n", read_byte);

            if('>' == *iterator) {
                result = iterator - start + 1;
                break;
            }
        }
        if (endIterator <= iterator){//buffer is too small
            result = -2;
        }
    }

    return result;
}
*/
